package com.gzwanchuang.xhgj.push;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.text.TextUtils;

import com.gzwanchuang.architecture.utils.LogUtil;
import com.gzwanchuang.xhgj.app.App;


import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

/**
 * Created by Jared on 2018/3/29.
 * 极光注册管理
 */

public class JPushHelper {

    private static Context appContext;

    public static void init(App application){
        appContext = application;
        JPushInterface.setDebugMode(true);  //设置为调试模式
        JPushInterface.init(application);
    }

    public static void setAlias(String alias){
        LogUtil.e("wang","开始设置别名 alias="+alias);
        mHandler.removeCallbacksAndMessages(null);
        // 调用 Handler 来异步设置别名
        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, alias));
    }



    private static final int MSG_SET_ALIAS = 1001;
    @SuppressLint("HandlerLeak")
    private static final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SET_ALIAS:
                    // 调用 JPush 接口来设置别名。
                    JPushInterface.setAlias(appContext,(String) msg.obj,mAliasCallback);
                    break;
                default:
            }
        }
    };

    private static final TagAliasCallback mAliasCallback = new TagAliasCallback() {
        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs ;
            switch (code) {
                case 0:
                    if(TextUtils.isEmpty(alias)){
                        logs ="取消别名设置成功：别名="+alias;
                    }else{
                        logs ="别名设置成功：别名="+alias;
                    }
                    break;
                case 6002:
                    if(TextUtils.isEmpty(alias)){
                        logs ="取消别名设置失败 3秒后重新设置：别名="+alias;
                    }else{
                        logs ="别名设置失败 3秒后重新设置：别名="+alias;
                    }
                    // 延迟 3 秒来调用 Handler 设置别名
                    mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 3);
                    break;
                default:
                    logs ="别名设置位置错误: code="+code;
            }
//            CrashReport.putUserData(appContext, "Jpush_frank", logs);   //日志上报
            LogUtil.e("wang",logs);
        }
    };


}
